package com.lu.netty.client;

import com.lu.netty.handler.SimpleClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;

/**
 * @author xiaolu
 * @version 1.0
 * @date 2021-02-02 23:09
 */
public class NettyClient {

    public static void main(String[] args) throws InterruptedException {

        String host = "localhost";
        int port = 8081;
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE,true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast(new SimpleClientHandler());
                    ch.pipeline().addLast(new StringEncoder());
                }
            });

            ChannelFuture f = b.connect(host, port).sync();

            // 发送数据
            f.channel().writeAndFlush("hello server");
            f.channel().writeAndFlush("\r\n");
            f.channel().closeFuture().sync();

            Object result = f.channel().attr(AttributeKey.valueOf("sss")).get();
            System.out.println("获取服务器返回的数据 ---> " + result.toString());

            // 长连接
            // 说明：
            // 1.从handler当中获取数据
            // 2.保证连接响应结果数据安全（多线程并发问题）


        } finally {
            workerGroup.shutdownGracefully();
        }

    }
}
